package com.ma.security;

import com.ma.entity.SysUser;
import com.ma.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/*
    登录过程系统不是从我们数据库中获取数据的，因此，我们需要重新定义这个查用户数据的过程，我们需要重写UserDetailsService接口。
 */
@Service
public class UserDetalisServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser=sysUserService.getAllByUsername(username);
        if (sysUser ==null){
            throw new UsernameNotFoundException("用户名或者密码错误！");
        }                                                                                  //权限信息
        return new AccountUser(sysUser.getId(),sysUser.getUsername(),sysUser.getPassword(),getUserAuthority(sysUser.getId()));
    }
    /*
        获取用户权限信息（角色，菜单权限）
        用户登录，调用调用UserDetailsService.loadUserByUsername()方法时候可以返回用户的权限信息。
     */
    public List<GrantedAuthority> getUserAuthority(Long id) {
        // 角色（ROLE_admin)  菜单操作权限 sys：user：list
        String authority=sysUserService.getUserAuthorityInfo(id); //ROLE_admin，ROLE_normal,sys:user:list
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
